import { RouteRecordRaw } from 'vue-router'
import { getRouters } from '@/api/menu'
import Layout from '@/layout/layout.vue'
import { constantRoutes } from '@/router/index'


interface PermissionState {
  routes: RouteRecordRaw[]
  addRoutes: RouteRecordRaw[]
  isRoutesLoaded: boolean
}

const state: PermissionState = {
  routes: [],
  addRoutes: [],
  isRoutesLoaded: false
}

const mutations = {
  SET_ROUTES: (state: PermissionState, routes: RouteRecordRaw[]) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
    state.isRoutesLoaded = true
  }
}

function filterAsyncRouter(asyncRouterMap: any[]): RouteRecordRaw[] {
  return asyncRouterMap.filter(route => {
    // 过滤掉不需要的路由
    if (['/login', '/register', '/404', '/', '/dashboard'].includes(route.path)) {
      return false
    }

    // 确保所有路由都使用 Layout 作为父组件
    if (!route.component || route.component === 'Layout') {
      route.component = Layout
    } else {
      // 如果是子路由，才处理具体组件
      try {
        let componentPath = route.component
          .replace(/^\/+|\/+$/g, '')  // 移除开头和结尾的斜杠
          .replace('#', '') // 移除#号
        
        // 如果路径不是以.vue结尾，添加.vue后缀
        if (!componentPath.endsWith('.vue')) {
          componentPath = `${componentPath}.vue`
        }
        
        // 尝试加载组件
        route.component = () => import(`@/views/${componentPath}`).catch(err => {
          console.error('加载组件失败，尝试加载index.vue:', componentPath, err)
          // 如果直接加载失败，尝试加载 index.vue
          if (!componentPath.includes('/index')) {
            return import(`@/views/${componentPath.replace('.vue', '')}/index.vue`)
          }
          throw err
        })
      } catch (error) {
        console.error('路由组件解析失败:', route.component, error)
        return false
      }
    }
    
    // 处理子路由
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    
    // 确保所有路由都在 Layout 内部渲染
    if (!route.meta) route.meta = {}
    route.meta.inLayout = true
    
    return true
  })
}

const actions = {
  generateRoutes({ commit, state }: any) {
    // 如果路由已经加载过，直接返回
    if (state.isRoutesLoaded && state.addRoutes.length > 0) {
      return state.addRoutes
    }

    return new Promise(async (resolve) => {
      const { data } = await getRouters()
      const accessedRoutes = filterAsyncRouter(data)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}